using Agron.Data.Contracts;

using System;
using System.Security;
using System.Security.Principal;


namespace Agron.Security.ClientLayer
{
    /// <summary>
    /// An <see cref="IIdentity"/> implementation for the system.
    /// </summary>
    public class AgronIdentity : IIdentity
    {
        private readonly UserProfile _profile;
        private readonly bool _isAuthenticated;

        /// <summary>
        /// Initializes a new instance of the <see cref="AgronIdentity"/> class.
        /// </summary>
        /// <param name="profile">A <see cref="UserProfile"/> object for the represented identity.</param>
        public AgronIdentity(UserProfile profile)
        {
            if (null == profile) throw new ArgumentNullException("profile");

            this._profile = profile;
            this._isAuthenticated = true;
        }

        /// <summary>
        /// Gets the user profile associated to the represented identity.
        /// </summary>
        /// <value>A <see cref="UserProfile"/> object for the represented identity.</value>
        public UserProfile Profile { get { return _profile; } }

        public static AgronIdentity GetCurrent()
        {
            if ((null != AgronPrincipal.Current) && (null != AgronPrincipal.Current.AgronIdentity))
                return AgronPrincipal.Current.AgronIdentity;
            else
                throw new SecurityException(Properties.Resources.AgronIdentityNotSet);
        }


        #region IIdentity Members

        /// <summary>
        /// Gets the type of authentication used.
        /// </summary>
        /// <value></value>
        /// <returns>The type of authentication used to identify the user.</returns>
        public string AuthenticationType { get { return Properties.Resources.AgronIdentityAuthenticationType; } }

        /// <summary>
        /// Gets a value that indicates whether the user has been authenticated.
        /// </summary>
        /// <value></value>
        /// <returns>true if the user was authenticated; otherwise, false.</returns>
        public bool IsAuthenticated { get { return this._isAuthenticated; } }

        /// <summary>
        /// Gets the name of the current user.
        /// </summary>
        /// <value></value>
        /// <returns>The name of the user on whose behalf the code is running.</returns>
        public string Name { get { return this._profile.Username; } }

        #endregion
    }
}
